using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using SG3L_RAG.Domain.Repositories;
using SG3L_RAG.Infrastructure.Logging;
using SG3L_RAG.Infrastructure.Persistence;
using SG3L_RAG.Infrastructure.Repositories;

namespace SG3L_RAG.Infrastructure
{
    public static class ServiceCollectionExtension
    {
        public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
        {
            // 获取数据库提供程序配置
            var databaseProvider = configuration["DatabaseProvider"] ?? "PostgreSQL";
            
            // 根据配置选择数据库提供程序
            switch (databaseProvider.ToUpper())
            {
                case "POSTGRESQL":
                    services.AddDbContext<SG3LDbContext>(options =>
                        options.UseNpgsql(configuration.GetConnectionString("PostgreSQL") ?? 
                            throw new InvalidOperationException("PostgreSQL连接字符串未配置"))
                    );
                    break;
                    
                case "MYSQL":
                    services.AddDbContext<SG3LDbContext>(options =>
                        options.UseMySQL(configuration.GetConnectionString("MySQL") ?? 
                            throw new InvalidOperationException("MySQL连接字符串未配置"))
                    );
                    break;
                    
                default:
                    throw new InvalidOperationException($"不支持的数据库提供程序: {databaseProvider}");
            }

            // 配置日志系统
            ConfigureLogging(services, configuration);

            // 注册仓储服务
            services.AddScoped(typeof(IRepository<>), typeof(Repository<>));

            return services;
        }

        private static void ConfigureLogging(IServiceCollection services, IConfiguration configuration)
        {
            // 清除默认日志提供程序
            services.AddLogging(builder => builder.ClearProviders());

            // 配置Serilog
            services.AddSerilog((serviceProvider, loggerConfiguration) =>
            {
                loggerConfiguration
                    .ReadFrom.Configuration(configuration)
                    .MinimumLevel.Debug()
                    .MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Information)
                    .MinimumLevel.Override("Microsoft.EntityFrameworkCore", Serilog.Events.LogEventLevel.Warning)
                    .Enrich.FromLogContext()
                    .Enrich.WithProperty("Application", "SG3L_RAG")
                    .WriteTo.Console(
                        outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}")
                    .WriteTo.File(
                        path: "Logs/log-.txt",
                        rollingInterval: RollingInterval.Day,
                        retainedFileCountLimit: 30,
                        outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}")
                    .WriteTo.Sink(new DatabaseSink(serviceProvider));
            });
        }
    }
}